
package com.ruoyi.merchant.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.merchant.utils.AliOssUtil;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("/merchant/common")
@Slf4j
@RequiredArgsConstructor
public class CommonUtilController {
    private final AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 1. 验证用户是否登录（若依框架自动验证token）
            Long merchantId = MerchantSecurityUtils.getMerchantId();
            log.info("商家{}上传文件：{}", merchantId, file.getOriginalFilename());

            // 2. 验证文件
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }

            // 3. 验证文件类型（只允许图片）
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return AjaxResult.error("只允许上传图片文件");
            }

            // 4. 验证文件大小（限制5MB）
            long maxSize = 5 * 1024 * 1024; // 5MB
            if (file.getSize() > maxSize) {
                return AjaxResult.error("文件大小不能超过5MB");
            }

            // 5. 生成文件名
            String originalFilename = file.getOriginalFilename();
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 按日期和商家ID分类存储：merchant/商家ID/日期/文件名
            LocalDateTime now = LocalDateTime.now();
            String datePath = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String objectName = String.format("merchant/%d/%s/%s%s",
                    merchantId, datePath, UUID.randomUUID().toString(), suffixName);

            // 6. 上传到OSS
            String uploadedPath = aliOssUtil.upload(file.getBytes(), objectName);

            log.info("文件上传成功，URL: {}", uploadedPath);
            return AjaxResult.success("上传成功", uploadedPath);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }
}
